package com.youtui.common.util;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;

public class JsonObjectMapper extends ObjectMapper {

	/**
	 * 将系统对象转化为string类型传输到前台,js直接显示某些对象会出现格式错误
	 */
	private static final long serialVersionUID = 4300249304535642877L;
 
	public JsonObjectMapper() {
		super();
		SimpleModule simpleModule = new SimpleModule();
		simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
		simpleModule.addSerializer(java.math.BigInteger.class, ToStringSerializer.instance);
		simpleModule.addSerializer(java.lang.Integer.class, ToStringSerializer.instance);
		/*格式化日期字符串*/
		simpleModule.addSerializer(java.util.Date.class, new JsonSerializer<Object>() {
			public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider)
					throws IOException, JsonProcessingException {
				String date = value.toString();
				try {
					if (date.indexOf("CST") > 0) {
						SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
						Date d = sdf.parse(date);
						date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(d);
					}
				} catch (Exception e) {
					System.out.println(e.getMessage());
				}finally{
					jgen.writeString(date);
				}
			}
		});

		//simpleModule.addSerializer(java.util.Date.class, ToStringSerializer.instance);
		simpleModule.addSerializer(java.sql.Timestamp.class, ToStringSerializer.instance);
		simpleModule.addSerializer(java.sql.Date.class, ToStringSerializer.instance);
		this.registerModule(simpleModule);
		
		 // 空值处理为空串 
        this.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() { 
            @Override 
            public void serialize(Object value, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessingException { 
                jg.writeString(""); 
            } 
        }); 
	}
}